package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "CookieServlet", urlPatterns = {"/cookie"})
public class CookieServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        //TODO Method stub generated by Lomboz
        Cookie cookie = null;
        //获取请求相关的cookie
        Cookie[] cookies = request.getCookies( );
        boolean newCookie = false;
        //判断Cookie ServletStudy是否存在
        if (cookies != null){
            for (int i = 0; i < cookies.length; i++){
                if (cookies[i].getName( ).equals("Chapter3")){
                    cookie = cookies[i];
                }
            }//end for
        }//end if
        if (cookie == null){
            newCookie=true;
            int maxAge=10000;
            //生成cookie对象
            cookie = new Cookie("Chapter3","hyl");
            cookie.setPath(request.getContextPath( ));
            cookie.setMaxAge(maxAge);
            response.addCookie(cookie);
        }//end if
        // 显示信息
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter( );
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Cookie Info</title>");
        out.println("</head>");
        out.println("<body>");
        out.println(
                "<h2> Information about the cookie named \"Chapter3\"</h2>");
        out.println("Cookie value: "+cookie.getValue( )+"<br>");
        if (newCookie){
            out.println("Cookie Max-Age:"+cookie.getMaxAge( )+"<br>");
            out.println("Cookie Path: "+cookie.getPath( )+"<br>");
        }
        out.println("</body>");
        out.println("</html>");
    }
}
